package com.example.aspect;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.server.HttpServerRequest;
import com.example.Mapper.LogMapper;
import com.example.annotation.AutoLog;
import com.example.pojo.LogInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.python.antlr.ast.Str;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.Time;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
@Aspect
public class AutoLogAspect {

    @Autowired
    private LogMapper logMapper;

    private String URL = "127.0.0.1:8083";

    @Pointcut("execution(* com.example.Controller.*.*(..)) &&  @annotation(com.example.annotation.AutoLog)")
    public void autoLogPointCut(){}

    @Before("autoLogPointCut()")
    public void autoLog(JoinPoint joinPoint){

        // 获取当前请求的 HttpServletRequest 对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 获取请求路径以及请求类型
        String url_ = request.getRequestURI();
        String method = request.getMethod();


//        // 获取所有请求参数，并将其转换为字符串
//        StringBuilder params = new StringBuilder();
//        Map<String, String[]> paramMap = request.getParameterMap();
//        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
//            String key = entry.getKey();
//            String value = Arrays.toString(entry.getValue());
//            params.append(key).append("=").append(value).append("&");
//        }
//        if (params.length() > 0) {
//            params.deleteCharAt(params.length() - 1);
//        }
//
//        log.info(url_+" " + method+" "+params.toString());

        String url = URL + url_;

        LogInfo logInfo = new LogInfo();
        logInfo.setServerAddress(url);
        logInfo.setLogType(method);
        logInfo.setStartTime(DateTime.now());

        log.info("操作日志插入-----------");
        logMapper.insert(logInfo);

    }

}
